package com.wuye.dao;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

@Repository("tool")
public class Tool {
	@Resource
	private HibernateTemplate hibernateTemplate;

	public JSONArray getListForPage(final String[] title, final String hql,
			final int offset, final int length) {
		JSONArray obj = hibernateTemplate.execute(new HibernateCallback() {

			public JSONArray doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				query.setFirstResult(offset);
				query.setMaxResults(length);

				List list = query.list();

				JSONArray array = new JSONArray();
				System.out.println(list.size());

				Iterator it = list.iterator();
				while (it.hasNext()) {
					Object[] sz = (Object[]) it.next();
					JSONObject json = new JSONObject();
					for (int j = 0; j < title.length; j++) {
						json.put(title[j], sz[j]);
					}
					array.add(json);
				}
				return array;
			}
		});
		return obj;
	}

	public int getListCount(String hql) {
		return hibernateTemplate.find(hql).size();
	}

	// 列表
	public Map getJSON(final String[] title, final String hql,
			final int offset, final int length) {
		Map map = new HashMap();
		map.put("total", getListCount(hql));
		map.put("rows", getListForPage(title, hql, offset, length));
		return map;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
}
